package com.wanban.adutils.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.*
import com.wanban.adutils.AdUtils
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.db.AdRoomUtils
import com.wanban.adutils.tools.AdConstants
import com.wanban.adutils.tools.RxUtils
import java.lang.ref.WeakReference

object ReopenAdTools {

    private var adId = 0L
    private var adType = 0
    private var appPackageName: String? = null
    // 基本上一次性回调，主要是在启动页加载广告的时候使用
    private var callback: OnLoadAdCallback? = null
    private var adActivity: WeakReference<Activity>? = null
    private var reopenAdTools: CommonAdTools? = null
    private val appLifeCallback by lazy { ApplicationLifeCallback() }
    private val activityLifeCallback by lazy { ActivityLifecycleCallback() }

    /**
     * 注册监听App的状态，不要在启动页注册
     */
    fun init(activity: Activity) {
        val adDao = AdRoomUtils.getInstance().adDao()
        val reopenAd = adDao.query(AdConstants.AD_ID_REOPEN_AD)
        if (reopenAd?.adInfo.isNullOrEmpty()) {
            Log.e(AdConstants.TAG, "ReopenAd -> 没有配置ReopenAd")
            return
        }
        reopenAdTools = CommonAdTools()
        adId = reopenAd.adId
        adType = reopenAd.adType
        Log.e(AdConstants.TAG, "ReopenAd -> 当前广告类型 -> ${getAdType(adType)} ")
        val lastIndex = activity::class.java.name.lastIndexOf(".")
        appPackageName = activity::class.java.name.subSequence(0, lastIndex).toString()
        Log.e(AdConstants.TAG, "ReopenAd -> Init  App的前缀包名：${appPackageName} ")
        ProcessLifecycleOwner.get().lifecycle.addObserver(appLifeCallback)
        AdUtils.appContext.registerActivityLifecycleCallbacks(activityLifeCallback)
    }

    private fun getAdType(adType: Int): String{
        return if (adType == AdConstants.ADTYPE_SPLASH) {
            "SPLASH"
        } else {
            "普通插屏"
        }
    }

    /** 加载开屏广告: 主要用在启动页面加载开屏广告 */
    fun loadAd(activity: Activity){
        if (reopenAdTools == null) {
            return
        }
        // 初始化先加载一个开屏广告
        if (isAdLoadSuccess()) {
            callback?.onAdLoaded()
            return
        }
        reopenAdTools?.loadAd(activity, adId, object: OnLoadAdCallback(){
            override fun onAdLoadFailed(errorCode: Int) {
                super.onAdLoadFailed(errorCode)
                Log.e(AdConstants.TAG, "ReopenAd -> 加载失败")
                callback?.onAdLoadFailed(errorCode)
            }

            override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                super.onAdLoaded(ad, *tag)
                Log.e(AdConstants.TAG, "ReopenAd -> 加载成功")
                callback?.onAdLoaded()
            }
        })
    }


    /** 显示 */
    fun showAd(activity: Activity){
        if (reopenAdTools == null) {
            return
        }
        Log.e(AdConstants.TAG, "ReopenAd -> 准备展示广告")
        reopenAdTools?.showAdInActivity(activity)
    }

    /**
     * 广告是否加载完成
     */
    fun isAdLoadSuccess(): Boolean{
        return reopenAdTools?.isAdLoadSuccess()?:false
    }

    /**
     * 释放广告
     */
    fun release(){
        ProcessLifecycleOwner.get().lifecycle.removeObserver(appLifeCallback)
        AdUtils.appContext.unregisterActivityLifecycleCallbacks(activityLifeCallback)
        reopenAdTools?.release()
        callback = null
    }
    
    
    class ActivityLifecycleCallback: Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
        override fun onActivityStarted(activity: Activity) {}
        override fun onActivityResumed(activity: Activity) {
            Log.d(AdConstants.TAG, "ReopenAd -> onActivityResumed " + activity::class.java.name)
            adActivity = WeakReference(activity)
        }
        override fun onActivityPaused(activity: Activity) {}
        override fun onActivityStopped(activity: Activity) {}
        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
        override fun onActivityDestroyed(activity: Activity) {}
    }

    private fun isMyAppActivity(activity: Activity): Boolean {
        val lastIndex = activity::class.java.name.lastIndexOf(".")
        val currentClassPackage = activity::class.java.name.subSequence(0, lastIndex).toString()
        Log.d(AdConstants.TAG, "ReopenAd -> onActivityPaused " + activity::class.java.name)
        if (currentClassPackage != appPackageName) {
            Log.d(AdConstants.TAG, "ReopenAd -> onActivityPaused -> 非本App页面显示")
            return false
        }
        return true
    }

    @Suppress("DEPRECATION")
    class ApplicationLifeCallback: LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun onResume(){
            if (reopenAdTools == null) {
                return
            }
            val activity = adActivity?.get()?:return
            if (!isMyAppActivity(activity)) {
                Log.d(AdConstants.TAG, "ReopenAd -> onActivityResumed -> 非本App页面显示")
                return
            }
            Log.d(AdConstants.TAG, "ReopenAd -> 从后台切回App " )
            RxUtils.timer(300) {
                showAd(activity)
            }
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun onPause(){
            if (reopenAdTools == null) {
                return
            }
            val activity = adActivity?.get()?:return
            if (!isMyAppActivity(activity)) {
                Log.e(AdConstants.TAG, "ReopenAd -> onActivityResumed -> 非本App页面显示")
                return
            }
            Log.e(AdConstants.TAG, "ReopenAd -> 从App切到后台，准备加载广告 " )
            // 加载广告
            loadAd(activity)
        }
    }

}